﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mamnontuoitho7.AppCode;
using System.Data;
using System.Text.RegularExpressions;

namespace mamnontuoitho7.module
{
    public partial class HomeDetails : System.Web.UI.Page
    {
        private mamnontuoitho7.AppCode.Article _article = new mamnontuoitho7.AppCode.Article();
        protected Product _product = new Product();
        protected General _general = new General();
        protected Comment _comment = new Comment();
        protected Rating _rating = new Rating();
        

        protected DataTable _dt, _dtLink, _dtComment;
        protected double rate;
        protected Double _start = 0;
        protected string _articleID;

        protected int _pageflag;
        protected int _currentbar = 1;


        protected int _totalPages;// tổng số trang chứa comment
        protected int _totalCommentNumber;//tong số comment cua bai viet này
        protected int _totalBars;// tổng số bar
        protected int _beginPage;// dung bên trang giao diện
        protected int _endPage;// dung bên trang giao diện
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["ArticleID"] != null && Request.QueryString["ArticleID"].ToString() != "")
            {
                string temp = Request.QueryString["ArticleID"].ToString();
                Match match = Regex.Match(temp, @"([0-9])$", RegexOptions.IgnoreCase);

                if (temp.Length <= 4 && match.Success)
                {
                   // Session["HomeDetails_productID"] = temp;
                    _articleID = temp;
                }
                else
                {
                    Response.Redirect("Home.aspx");
                }
            }

            try
            {
                // update comment
                if (Request.Form["txtNewComment"] != "" && Request.Form["hidCommentID"] != null && Request.Form["hidStatus"] != null)
                {
                    string _commentID = Request.Form["hidCommentID"].ToString();
                    string _content = Request.Form["txtNewComment"].ToString();
                    _comment.ContentCommentUpdate(_commentID, _content);
                }

                // delete comment by link
                if (Request.QueryString["b"] != null)
                {
                    if (Session["role"].ToString() == "1" || Session["role"].ToString() == "2" || Session["role"].ToString() == "5" || Session["role"].ToString() == "7")
                    {
                        string tempB = Request.QueryString["b"].ToString();
                        Match matchA = Regex.Match(tempB, @"([0-9])$", RegexOptions.IgnoreCase);
                        if (tempB.Length <= 4 && matchA.Success)
                        {
                            // string _commentID = Request.QueryString["b"].ToString();
                            _comment.CommentDelete(tempB);
                        }
                    }
                    
                }

                _dt = _article.GetArticleByID(_articleID);// lấy thông tin product(article) hien hành

                string bbbb = _dt.Rows[0]["ArticleTypeID"].ToString();
                _dtLink = _article.GetSomeTopArticleByType("6", _dt.Rows[0]["ArticleTypeID"].ToString());// lấy 6 product mói nhất -> link bài viết liên quan

                //////////////////////////////////////////begin paging
                _totalCommentNumber = _comment.TotalCommentOfOneProduct(_articleID).GetValueOrDefault();
                _totalPages = _general.Divide(_totalCommentNumber, ConstantClass._pageStepComment);
                _totalBars = _general.Divide(_totalPages, ConstantClass._barStepComment);



                if (Request.QueryString["page"] != null)// khi nhận giá trị biến ["page"] trên link khi bấm vào ô số
                {
                    string temp = Request.QueryString["page"].ToString();
                    Match match = Regex.Match(temp, @"([0-9])$", RegexOptions.IgnoreCase);

                    if (temp.Length <= 4 && match.Success)
                    {
                        _pageflag = Convert.ToInt16(temp);// trang hiện hành
                        if (_pageflag <= _totalPages)
                        {
                            _currentbar = _general.Divide(_pageflag, ConstantClass._barStepComment);
                            Response.Cookies["CurrentBar"].Value = _currentbar.ToString();
                        }
                        else { 
                            _pageflag = 1; _currentbar = 1;
                            Response.Cookies["CurrentBar"].Value = _currentbar.ToString();
                        }
                    }

                }
                if (Request.QueryString["page"] == null && Request.QueryString["a"] == null)// khi mới vào trang
                {
                    _currentbar = 1;
                    _pageflag = 1;
                    Response.Cookies["CurrentBar"].Value = "1";
                }

                if (Request.QueryString["a"] != null && Request.QueryString["a"] == "1") // khi bấm vào ô >> (next)
                {
                    _currentbar = Int16.Parse(Request.Cookies["CurrentBar"].Value);
                    if (_currentbar < _totalBars)
                    {
                        _currentbar += 1;
                        Response.Cookies["CurrentBar"].Value = _currentbar.ToString();
                    }
                    _pageflag = (_currentbar - 1) * ConstantClass._barStepComment + 1;
                }

                if (Request.QueryString["a"] != null && Request.QueryString["a"] == "-1") // khi bấm vào ô << (previous)
                {
                    _currentbar = Int16.Parse(Request.Cookies["CurrentBar"].Value);
                    if (_currentbar > 1)
                    {
                        _currentbar -= 1;
                        Response.Cookies["CurrentBar"].Value = _currentbar.ToString();
                    }
                    _pageflag = (_currentbar - 1) * ConstantClass._barStepComment + 1;
                }


                _dtComment = _comment.GetCommentPaged(_pageflag, ConstantClass._pageStepComment, _articleID);
                _beginPage = (_currentbar - 1) * ConstantClass._barStepComment + 1;
                _endPage = _currentbar * ConstantClass._barStepComment;

                if (_endPage > _totalPages)
                {
                    _endPage = _totalPages;
                }
                /////////////////////////////////////////end



                if (Request.QueryString["ArticleID"] != null && Request.QueryString["Comment"] == null)// chỉ định duy nhât là refresh hay chạy lại link mới tang số view
                {
                    if (!IsPostBack)
                    {
                        _product.IncreaseProductView(_articleID);
                    }
                }
                if (Request.QueryString["rate"] == "1" | Request.QueryString["rate"] == "2" | Request.QueryString["rate"] == "3" | Request.QueryString["rate"] == "4" | Request.QueryString["rate"] == "5")// đánh giá
                {
                    if (!IsPostBack)
                    {
                        if (Session["username"].ToString() != "")
                        {
                            string rate = Request.QueryString["rate"].ToString();
                            _rating.RatingCreateOrRecreate(_articleID, Session["memberID"].ToString(), rate);
                        }
                        else
                        {
                            String script = "<script language=JavaScript>alert('Đăng nhập để có thể đánh giá bài viết.');showhide('loginform');</script>";
                            Page.ClientScript.RegisterStartupScript(typeof(Page), "alert", script);
                        }
                    }

                }


                _start = _rating.AverageMark(_articleID) * 16;
                Session["Common_articleTypeID"] = "1";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Response.Redirect(ConstantClass._errorLoginPage);
            }
        }

        protected void btnPostComment_Click(object sender, EventArgs e)
        {
            try
            {
                bool d = _comment.CommentCreate(_articleID, Session["memberID"].ToString(), txtComment.Text.Trim());
                txtComment.Text = "";
                _totalCommentNumber = _comment.TotalCommentOfOneProduct(_articleID).GetValueOrDefault();
                _totalPages = _general.Divide(_totalCommentNumber, ConstantClass._pageStepComment);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Response.Redirect(ConstantClass._errorLoginPage);
            }
            // Comment=1 : tranh việc post cmt xong tăng số view
            Response.Redirect("HomeDetails.aspx?ArticleID=" + _articleID + "&Comment=1&page=" + _totalPages);

        }
    }
}